package com.tom.cfg;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * zookeeper服务注册配置
 *
 * @author yanghongjun19
 * @date 2020/12/27
 **/
@Configuration
@Slf4j
public class ZookeeperCfg {

    @Value("${zookeeper.address}")
    private String address;

    @Value("${zookeeper.path}")
    private String path;

    @Value("${zookeeper.timeout}")
    private int timeOut;

    @Value("${server.host}")
    private String host;

    @Value("${server.port}")
    private int port;

    private ZooKeeper zk;

    @Bean
    public ZooKeeper zooKeeper() throws Exception {
        zk = new ZooKeeper(address, timeOut, (v) -> {
            if (v.getState() == Watcher.Event.KeeperState.SyncConnected) {//连接成功
                try {
                    zk.create(path, (host + ":" + port).getBytes(),
                            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
                    log.info("服务注册成功");
                } catch (Exception e) {
                    log.warn("服务注册失败:" + e.getMessage());
                }
            }
        });

        return zk;
    }
}
